<template>
  <div class="article-detail-page">
    <div class="article-container">
      <!-- 文章头部 -->
      <div class="article-header">
        <h1 class="article-title">{{ articleInfo.title }}</h1>
        <div class="article-meta-info">
          <span class="meta-item">
            <i class="fas fa-eye"></i>
            {{ articleInfo.viewCount || 0 }} 次阅读
          </span>
          <span class="meta-item">
            <i class="fas fa-heart"></i>
            {{ articleInfo.likeCount || 0 }} 点赞
          </span>
          <span class="meta-item">
            <i class="fas fa-comment-alt"></i>
            {{ articleInfo.commentCount || 0 }} 条评论
          </span>
          <span class="meta-item">
            <i class="fas fa-calendar"></i>
            {{ articleInfo.publishDate || '未知日期' }}
          </span>
          <span class="meta-item" v-if="articleInfo.author">
            <i class="fas fa-user"></i>
            {{ articleInfo.author }}
          </span>
        </div>
      </div>

      <!-- 富文本内容 -->
      <div class="article-content">
        <div class="richtext" v-html="articleInfo.content"></div>
      </div>

      <!-- 互动按钮区域 -->
      <div class="article-actions">
        <button
          class="action-btn like-btn"
          :class="{ liked: articleInfo.isLike === 0 }"
          @click="toggleLike"
        >
          <i class="fas fa-heart"></i>
          <span>{{ articleInfo.isLike === 0 ? '已点赞' : '点赞' }}</span>
          <span class="count">{{ articleInfo.likeCount || 0 }}</span>
        </button>

        <button class="action-btn share-btn" @click="showShareModal">
          <i class="fas fa-share-alt"></i>
          <span>转发</span>
        </button>
      </div>

      <!-- 评论区域 -->
      <div class="comments-section">
        <h3 class="section-title">
          <span>评论 ({{ articleInfo.commentCount || 0 }})</span>
        </h3>

        <!-- 评论输入框 -->
        <div class="comment-input-area">
          <n-input
            class="comment-input"
            v-model:value="newComment"
            placeholder="写下你的评论..."
            maxlength="100"
          >
            <template #suffix>
              <n-button @click="addComment" tertiary circle type="primary">
                <template #icon>
                  <n-icon><IosSend /></n-icon>
                </template>
              </n-button>
            </template>
          </n-input>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <div class="comment-item" v-for="comment in comments" :key="comment.id">
            <n-avatar class="avatar" :src="comment?.user?.avatar" round />
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment?.user?.username }}</span>
                <span class="badge author-badge" v-if="comment.isAuthor">作者</span>
                <span class="badge user-badge" v-if="comment.isLoginUser">我</span>
                <span class="comment-time">{{ comment.createTime }}</span>
              </div>
              <p class="comment-text">{{ comment.content }}</p>
            </div>
          </div>

          <!-- 空状态提示 -->
          <div v-if="!comloading && comments.length === 0" class="comment-tip"> 暂无评论 </div>

          <!-- 加载状态 -->
          <div v-if="comloading" class="comment-tip"> 加载中... </div>

          <!-- 没有更多数据提示 -->
          <div v-if="!comloading && isLastPage && comments.length > 0" class="comment-tip">
            暂无更多
          </div>
          <div
            v-if="!comloading && comments.length !== 0 && !isLastPage"
            class="load-more"
            @click="loadMoreComments"
          >
            <span>点击加载更多评论</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 转发弹窗 - 显示公众号二维码 -->
    <div v-if="showShare" class="share-modal-overlay" @click="closeShareModal">
      <div class="share-modal" @click.stop>
        <div class="share-modal-header">
          <h3>转发到公众号</h3>
          <button class="close-btn" @click="closeShareModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="share-modal-content">
          <div class="qr-code-container">
            <div class="qr-code">
              <img :src="qrCodeUrl" alt="公众号二维码" />
            </div>
            <p class="qr-tip">请到公众号内完成转发</p>
            <p class="qr-desc">扫描上方二维码关注公众号，在公众号内完成文章转发</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, watch } from 'vue';
  import { useRoute } from 'vue-router';
  import { getCommentListApi, addCommonApi, likeChapterApi } from '@/api/course';
  import { IosSend } from '@vicons/ionicons4';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useMessage } from 'naive-ui';
  import { useUserStore } from '@/store/modules/user';

  const route = useRoute();
  const message = useMessage();
  const userStore = useUserStore();

  const articleId = ref('');
  const articleInfo = ref<any>({
    title: '',
    content: '',
    viewCount: 0,
    likeCount: 0,
    commentCount: 0,
    publishDate: '',
    author: '',
    isLike: 1, // 1-未点赞，0-已点赞
  });

  // 转发相关
  const showShare = ref(false);
  const qrCodeUrl = ref('https://via.placeholder.com/200x200?text=公众号二维码'); // 这里应该是真实的公众号二维码地址

  // 评论相关
  const newComment = ref('');
  const comments = ref<any[]>([]);
  const pageNum = ref(1);
  const pageSize = 10;
  const comloading = ref(false);
  const isLastPage = ref(false);
  const pages = ref(0);

  // 监听路由变化
  watch(
    () => route.query,
    async (newParams: any) => {
      if (newParams.id) {
        articleId.value = newParams.id;
        await getArticleDetail();
        await getCommonList(true);
      }
    },
    { immediate: true }
  );

  // 获取文章详情（这里使用假数据，实际应该调用 API）
  async function getArticleDetail() {
    // 模拟 API 调用
    await new Promise((resolve) => setTimeout(resolve, 300));

    // 假数据 - 实际应该调用 API
    articleInfo.value = {
      id: articleId.value,
      title: 'ChatGPT 4.0 全面解析：从原理到应用',
      content: `
        <h2>引言</h2>
        <p>ChatGPT 4.0 是 OpenAI 最新发布的大型语言模型，它在多个方面都有了显著的提升。本文将深入探讨 ChatGPT 4.0 的技术原理、应用场景和未来发展趋势。</p>
        
        <h2>技术原理</h2>
        <p>ChatGPT 4.0 基于 Transformer 架构，采用了更大规模的参数和更先进的训练技术。相比前代版本，它在理解能力、生成质量和多模态处理方面都有了质的飞跃。</p>
        
        <h3>核心特性</h3>
        <ul>
          <li>更强的语言理解能力</li>
          <li>更准确的回答生成</li>
          <li>支持多模态输入输出</li>
          <li>更好的上下文记忆</li>
        </ul>
        
        <h2>应用场景</h2>
        <p>ChatGPT 4.0 在各个领域都有广泛的应用，包括但不限于：</p>
        <ol>
          <li>内容创作：帮助用户生成文章、故事、诗歌等</li>
          <li>代码生成：辅助程序员编写和调试代码</li>
          <li>教育培训：提供个性化的学习辅导</li>
          <li>客户服务：智能客服系统</li>
        </ol>
        
        <h2>未来展望</h2>
        <p>随着技术的不断发展，ChatGPT 4.0 将在更多领域发挥重要作用。我们期待看到它在科学研究、医疗健康、商业决策等方面带来更多创新。</p>
        
        <p>总的来说，ChatGPT 4.0 代表了当前 AI 技术的最高水平，它的出现将极大地推动人工智能在各个领域的应用和发展。</p>
      `,
      viewCount: 1234,
      likeCount: 56,
      commentCount: 12,
      publishDate: '2024-01-15',
      author: '张教授',
      isLike: 1,
    };
  }

  // 获取评论列表
  async function getCommonList(isRefresh = false) {
    if (comloading.value || (isLastPage.value && !isRefresh)) return;

    comloading.value = true;
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize,
        bizType: 1, // 1-文章，0-视频章节
        bizId: articleId.value,
      };

      const data: any = await getCommentListApi(params);

      let list = data.records || [];
      if (isRefresh) {
        comments.value = list;
        pageNum.value = 1;
        isLastPage.value = false;
      } else {
        comments.value = [...comments.value, ...list];
      }

      pages.value = data.pages;

      if (list.length < pageSize) {
        isLastPage.value = true;
      } else {
        pageNum.value++;
      }
    } catch (error) {
      console.error('error:', error);
    } finally {
      comloading.value = false;
    }
  }

  // 添加评论
  const addComment = async () => {
    if (!newComment.value.trim()) {
      message.warning('请输入评论内容');
      return;
    }

    try {
      const params = {
        content: newComment.value,
        bizType: 1, // 1-文章，0-视频章节
        bizId: articleId.value,
      };

      const { code, data } = await addCommonApi(params);
      if (code == ResultEnum.SUCCESS) {
        comments.value.unshift({
          id: data,
          createTime: '刚刚',
          likeCount: 0,
          isLike: false,
          isAuthor: false,
          isLoginUser: true,
          user: {
            username: userStore?.info?.username,
            avatar: userStore?.info?.avatar,
          },
          ...params,
        });

        articleInfo.value.commentCount++;
        message.success('评论发表成功');
      } else {
        message.error('发表评论失败，请稍后重试！');
      }
    } catch (error) {
      message.error('发表评论失败，请稍后重试！');
    }

    newComment.value = '';
  };

  // 加载更多评论
  const loadMoreComments = () => {
    getCommonList();
  };

  // 点赞功能
  const toggleLike = async () => {
    try {
      const params = {
        bizType: 1, // 1-文章，0-视频章节
        bizId: articleId.value,
      };

      const { code, data } = await likeChapterApi(params);
      if (code == ResultEnum.SUCCESS) {
        if (data) {
          // 已点赞，取消点赞
          articleInfo.value.isLike = 1;
          articleInfo.value.likeCount = Math.max(0, (articleInfo.value.likeCount || 0) - 1);
        } else {
          // 未点赞，点赞
          articleInfo.value.isLike = 0;
          articleInfo.value.likeCount = (articleInfo.value.likeCount || 0) + 1;
        }
      } else {
        message.error('点赞失败，请稍后重试！');
      }
    } catch (error) {
      message.error('点赞失败，请稍后重试！');
    }
  };

  // 显示转发弹窗
  const showShareModal = () => {
    showShare.value = true;
  };

  // 关闭转发弹窗
  const closeShareModal = () => {
    showShare.value = false;
  };

  onMounted(() => {
    if (route.query.id) {
      articleId.value = route.query.id as string;
      getArticleDetail();
      getCommonList(true);
    }
  });
</script>

<style scoped>
  .article-detail-page {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .article-container {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 40px;
  }

  /* 文章头部 */
  .article-header {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;
  }

  .article-title {
    font-size: 32px;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 20px;
    line-height: 1.4;
  }

  .article-meta-info {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    color: #666;
    font-size: 14px;
  }

  .meta-item {
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .meta-item i {
    color: #999;
  }

  /* 文章内容 */
  .article-content {
    margin-bottom: 30px;
    padding-bottom: 30px;
    border-bottom: 1px solid #eee;
  }

  .article-content .richtext {
    line-height: 1.8;
    color: #333;
  }

  .article-content .richtext h2,
  .article-content .richtext h3 {
    margin-top: 30px;
    margin-bottom: 15px;
    font-weight: 600;
  }

  .article-content .richtext ul,
  .article-content .richtext ol {
    margin: 15px 0;
    padding-left: 30px;
  }

  .article-content .richtext li {
    margin: 8px 0;
    line-height: 1.8;
  }

  /* 互动按钮区域 */
  .article-actions {
    display: flex;
    gap: 20px;
    padding: 20px 0;
    margin-bottom: 30px;
    border-bottom: 1px solid #eee;
  }

  .action-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    background: none;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    cursor: pointer;
    font-size: 16px;
    color: #555;
    transition: all 0.3s ease;
    padding: 10px 20px;
  }

  .action-btn:hover {
    background: #f5f7fa;
    border-color: #cbd5e0;
  }

  .like-btn.liked {
    color: #ff4d4f;
    border-color: #ff4d4f;
    background: #fff1f0;
  }

  .like-btn.liked i {
    animation: pulse 0.5s;
  }

  .action-btn i {
    font-size: 18px;
  }

  .action-btn .count {
    font-weight: 600;
  }

  @keyframes pulse {
    0% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.3);
    }
    100% {
      transform: scale(1);
    }
  }

  /* 评论区域 */
  .comments-section {
    margin-top: 30px;
  }

  .section-title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #2c3e50;
  }

  .comment-input-area {
    margin-bottom: 30px;
  }

  .comment-input {
    padding: 10px 0;
  }

  .comment-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .comment-item {
    display: flex;
    gap: 15px;
    background: #f9fbfd;
    border: 1px solid #eef2f7;
    padding: 20px;
    border-radius: 8px;
  }

  .avatar {
    width: 40px;
    height: 40px;
    flex-shrink: 0;
  }

  .comment-content {
    flex: 1;
  }

  .comment-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
  }

  .comment-author {
    font-weight: 600;
    color: #2c3e50;
  }

  .badge {
    font-size: 12px;
    padding: 2px 6px;
    border-radius: 3px;
  }

  .author-badge {
    background: #fff7e6;
    color: #fa8c16;
  }

  .user-badge {
    background: #e6f7ff;
    color: #1890ff;
  }

  .comment-time {
    color: #999;
    font-size: 13px;
    margin-left: auto;
  }

  .comment-text {
    margin: 0;
    line-height: 1.6;
    color: #333;
  }

  .comment-tip {
    text-align: center;
    height: 60px;
    line-height: 60px;
    color: #999;
    font-size: 16px;
  }

  .load-more {
    text-align: center;
    color: #1890ff;
    padding: 15px;
    cursor: pointer;
    font-weight: 500;
    margin-top: 10px;
    border-radius: 8px;
    transition: background 0.3s;
  }

  .load-more:hover {
    background: #f0f7ff;
  }

  /* 转发弹窗 */
  .share-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    backdrop-filter: blur(5px);
  }

  .share-modal {
    background: white;
    border-radius: 16px;
    width: 90%;
    max-width: 400px;
    overflow: hidden;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  }

  .share-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #e5e7eb;
  }

  .share-modal-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #111827;
  }

  .close-btn {
    background: none;
    border: none;
    font-size: 18px;
    color: #6b7280;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    transition: all 0.2s;
  }

  .close-btn:hover {
    background: #f3f4f6;
    color: #374151;
  }

  .share-modal-content {
    padding: 30px 24px;
    text-align: center;
  }

  .qr-code-container {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .qr-code {
    width: 200px;
    height: 200px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 10px;
    background: white;
    margin-bottom: 20px;
  }

  .qr-code img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .qr-tip {
    font-size: 16px;
    font-weight: 600;
    color: #111827;
    margin-bottom: 10px;
  }

  .qr-desc {
    font-size: 14px;
    color: #6b7280;
    line-height: 1.6;
    margin: 0;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .article-detail-page {
      padding: 10px;
    }

    .article-container {
      padding: 20px;
    }

    .article-title {
      font-size: 24px;
    }

    .article-meta-info {
      gap: 15px;
      font-size: 12px;
    }

    .article-actions {
      flex-direction: column;
      gap: 10px;
    }

    .action-btn {
      width: 100%;
      justify-content: center;
    }
  }
</style>